#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
day 29 homework
"""
# 1.文件的上传、下载
# 2.结合用户认证
# 要求：
# 1.tcp协议粘包的问题，使用struct模块解决粘包问题
# 2.传递的所有的信息都尽量是json格式
# 3.再server端用上反射

import os
import json
import struct
import hashlib
from socket import socket


class HomePage(object):
    def get_md5(self, salting, data):
        """
        md5动态加密
        :param salting: 用户名
        :param data: 密文
        :return: 再加密
        """
        obj = hashlib.md5((salting + 'sdu2c9s.fd9s0').encode('utf-8'))
        obj.update(data.encode('utf-8'))
        return obj.hexdigest()


    def get_size(self, data):
        data_size = struct.pack('i', data)
        return data_size


    def login(self):
        while True:
            msg = conn.recv(1024).decode('utf-8')
            info = json.loads(msg)
            with open('user_info.txt', 'r', encoding='utf-8') as f:
                user, pwd = f.read().strip().split('|')
            if info['user'] == user and self.get_md5(info['user'], info['pwd']) == pwd:
                conn.send('T'.encode('utf-8'))
                break
            else:
                conn.send('F'.encode('utf-8'))
                continue


    def file_down(self):
        file_name_size = conn.recv(4)
        file_name_size = struct.unpack('i', file_name_size)[0]
        file_name = conn.recv(file_name_size).decode('utf-8')
        size = conn.recv(4)
        size = struct.unpack('i', size)[0]
        with open(os.path.join('file', file_name), 'wb') as f:
            count = 0
            while size > count:
                msg = conn.recv(1024)
                f.write(msg)
                count += 1024
        conn.send('上传成功'.encode('utf-8'))


    def file_up(self):
        file_list = os.listdir('file')
        file_list = json.dumps(file_list)
        conn.send(file_list.encode('utf-8'))
        file = conn.recv(1024).decode('utf-8')
        path = os.path.join('file', file)
        file_size = os.path.getsize(path)
        size = self.get_size(file_size)
        file_name = os.path.basename(path)
        file_name_size = self.get_size(len(file_name))
        conn.send(file_name_size)
        conn.send(file_name.encode('utf-8'))
        conn.send(size)
        with open(path, 'rb') as f:
            count = 0
            while file_size > count:
                res = f.read(1024)
                conn.send(res)
                count += 1024


sk = socket()
sk.bind(('127.0.0.1', 9001))
sk.listen()
conn, addr = sk.accept()
while True:
    home_dict = {'1': 'login', '2': 'file_down', '3': 'file_up'}
    num = conn.recv(1024).decode('utf-8')
    obj = HomePage()
    getattr(obj, home_dict[num])()
    conn.close()
